<template>
  <div class="dependency-pie-chart">
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <h3>📊 依赖类型分布</h3>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="chartData" class="chart-container">
        <v-chart
          class="chart"
          :option="chartOption"
          autoresize
        />
      </div>

      <div v-else class="empty-container">
        <el-empty description="暂无依赖数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, type Ref } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
} from 'echarts/components';
import VChart from 'vue-echarts';
import { AnalysisDataService } from '../services/analysis-data';

// 注册 ECharts 组件
use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
]);

/**
 * 依赖类型统计数据接口
 */
interface IDependencyTypeStat {
  name: string;
  value: number;
  type: string;
}

// 响应式数据
const loading: Ref<boolean> = ref(true);
const chartData: Ref<IDependencyTypeStat[] | null> = ref(null);
const analysisService = AnalysisDataService.getInstance();

/**
 * 图表配置选项
 */
const chartOption = computed(() => {
  if (!chartData.value) return {};

  // 颜色配置
  const colors = {
    local: '#67c23a',
    package: '#409eff',
    workspace: '#e6a23c',
    root: '#f56c6c',
  };

  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 12,
      },
    },
    series: [
      {
        name: '依赖类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: chartData.value.map(item => ({
          ...item,
          itemStyle: {
            color: colors[item.type as keyof typeof colors] || '#909399',
          },
        })),
      },
    ],
  };
});

/**
 * 加载依赖类型统计数据
 */
const loadChartData = async (): Promise<void> => {
  try {
    loading.value = true;

    // 检查是否已有数据
    let currentData = analysisService.getCurrentAnalysisData();

    if (!currentData) {
      // 加载数据（路径从环境变量获取）
      await analysisService.loadAnalysisData();
    }

    const stats = analysisService.getDependencyTypeStats();
    chartData.value = stats;
  } catch (error) {
    console.error('加载依赖类型统计数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadChartData();
});
</script>

<style scoped>
.dependency-pie-chart {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.loading-container {
  padding: 20px;
}

.chart-container {
  padding: 20px;
  height: 400px;
}

.chart {
  width: 100%;
  height: 100%;
}

.empty-container {
  padding: 40px;
  text-align: center;
}
</style>
